import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

interface UserInfo {
	avatar: string;
	avator: string;
	id: string;
	nickname: string;
	password: string;
	role: string;
	rolename: string;
	state: string;
	tip: string;
	username: string;
}

interface UserState {
	isLoggedIn: boolean;
	accessToken: string | null;
	refreshToken: string | null;
	userInfo: UserInfo | null;
	loading: boolean;
	error: string | null;
}

const initialState: UserState = {
	isLoggedIn: false,
	accessToken: null,
	refreshToken: null,
	userInfo: null,
	loading: false,
	error: null,
};

// 刷新token的异步thunk
export const refreshTokenAsync = createAsyncThunk(
	'user/refreshToken',
	async (_, { getState, rejectWithValue }) => {
		try {
			const { user } = getState() as { user: UserState };

			if (!user.refreshToken) {
				return rejectWithValue('No refresh token available');
			}

			const response = await axios.post('/api/refresh-token', {
				refreshToken: user.refreshToken
			});

			return response.data;
		} catch (error) {
			return rejectWithValue('Failed to refresh token');
		}
	}
);

const userSlice = createSlice({
	name: 'user',
	initialState,
	reducers: {
		loginSuccess: (state, action) => {
			state.isLoggedIn = true;
			state.accessToken = action.payload.accessToken;
			state.refreshToken = action.payload.refreshToken;
			state.userInfo = action.payload.userInfo;
			state.error = null;
		},
		logout: (state) => {
			state.isLoggedIn = false;
			state.accessToken = null;
			state.refreshToken = null;
			state.userInfo = null;
		},
		setError: (state, action) => {
			state.error = action.payload;
		},
		clearError: (state) => {
			state.error = null;
		},
		updateAccessToken: (state, action) => {
			state.accessToken = action.payload;
		}
	},
	extraReducers: (builder) => {
		builder
			.addCase(refreshTokenAsync.pending, (state) => {
				state.loading = true;
			})
			.addCase(refreshTokenAsync.fulfilled, (state, action) => {
				state.loading = false;
				state.accessToken = action.payload.accessToken;
				// 可选：如果后端也返回新的refreshToken
				if (action.payload.refreshToken) {
					state.refreshToken = action.payload.refreshToken;
				}
			})
			.addCase(refreshTokenAsync.rejected, (state, action) => {
				state.loading = false;
				state.error = action.payload as string;
				// 刷新失败时，可能需要登出用户
				state.isLoggedIn = false;
				state.accessToken = null;
				state.refreshToken = null;
				state.userInfo = null;
			});
	}
});

export const {
	loginSuccess,
	logout,
	setError,
	clearError,
	updateAccessToken
} = userSlice.actions;

export default userSlice.reducer;